package com.bookstore.controller;

import com.bookstore.dto.CartItemDTO;
import com.bookstore.entity.User;
import com.bookstore.security.JwtTokenProvider;
import com.bookstore.service.CartService;
import com.bookstore.service.UserHistoryService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/api/cart")
@Slf4j
public class CartController {

    @Autowired
    private CartService cartService;
    
    @Autowired
    private UserHistoryService userHistoryService;

    @Autowired
    private JwtTokenProvider jwtTokenProvider;

    @PostMapping("/add")
    public ResponseEntity<?> addToCart(@RequestBody CartItemDTO cartItemDTO) {
        Authentication auth = SecurityContextHolder.getContext().getAuthentication();
        Long userId = ((User) auth.getPrincipal()).getId();
        Long bookId = cartItemDTO.getBookId();
        cartItemDTO.setUserId(userId);

        // 修改为新增或更新购物车
        ResponseEntity responseEntity = cartService.addOrUpdateCart(cartItemDTO);
        
        // 记录添加到购物车的历史
        try {
            userHistoryService.addHistory(userId, bookId, "CART");
        } catch (Exception e) {
            log.error("记录购物车历史失败: " + e.getMessage(), e);
        }
        
        return ResponseEntity.ok(responseEntity);
    }

    @GetMapping
    public ResponseEntity<?> getCartItems() {
        Authentication auth = SecurityContextHolder.getContext().getAuthentication();
        Long userId = ((User) auth.getPrincipal()).getId();
        return cartService.getCartItems(userId);
    }

    @PutMapping("/{cartId}/{quantity}")
    public ResponseEntity<?> updateCartItem(
            @PathVariable Long cartId,
            @PathVariable Integer quantity) {
        return cartService.updateCartItem(cartId, quantity);
    }

    @DeleteMapping("/{cartId}")
    public ResponseEntity<?> removeFromCart(@PathVariable Long cartId) {
        return cartService.removeFromCart(cartId);
    }

    @DeleteMapping("/remove-batch/{ids}")
    public ResponseEntity<?> removeFromCart(@PathVariable String ids) {
        String[] split = ids.split(",");
        List<String> strings = Arrays.asList(split);
        List<Long> idList = strings.stream().map(d -> Long.parseLong(d)).collect(Collectors.toList());
        return cartService.removeByIds(idList);
    }

    @DeleteMapping("/clear")
    public ResponseEntity<?> clear() {
        Authentication auth = SecurityContextHolder.getContext().getAuthentication();
        Long userId = ((User) auth.getPrincipal()).getId();
        cartService.clear(userId);
        return ResponseEntity.ok("清空成功");
    }

    @GetMapping("/count")
    public ResponseEntity<?> getCartCount() {
        Authentication auth = SecurityContextHolder.getContext().getAuthentication();
        Long userId = ((User) auth.getPrincipal()).getId();
        return ResponseEntity.ok(cartService.getCartItems(userId).getBody().size());
    }
}